package com.zzy._03_xhr;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 同步消息
 * 消费者
 */
public class Consumer {

    public static void main(String[] args) throws Exception {
        // 1.创建一个消费者对象
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumer_xhr_group");
        // 2.设置NameServer的地址
        consumer.setNamesrvAddr("localhost:9876");

        // 3.拿到生产者的主题topic,和二级分类tag  tag可以是所有或者某个
        consumer.subscribe("xhr_topic", "xhr_tag");
        // 4.注册回调实现类来处理从broker拉取回来的消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                try {
                    // 4.1.遍历消息集合
                    for (MessageExt msg : msgs) {
                        // 4.2.得到消息对象
                        System.out.println(new String(msg.getBody(), StandardCharsets.UTF_8));
                    }
                    // 4.3消费成功，消息签收
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 如果消费失败，重新发一次消息
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });
        // 启动消费者
        consumer.start();
    }
}
